<template>
  <div class="settings">
    <van-nav-bar safe-area-inset-top placeholder title="EV Charger Setting" left-arrow fixed @click-left="onClickLeft" />
    <div class="marginTop15">
      <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
          <van-cell-group>
            <van-cell title="Max Power" :value="`${MaxPower}W`" />
            <van-cell title="Communication Version" :value="`${ComType==0?'Wi-Fi':'4G-LTE'}`" />
            <van-cell title="Main Firmware Version" :value="`${FirmwareVersion_Main}`" />
            <van-cell title="Main Bootloader Version" :value="`${Bootloader_Version}`" />
          </van-cell-group>
          <van-divider>settings</van-divider>
          <van-form @submit="setCharger">
            <van-collapse v-model="activeNames">
              <van-collapse-item title="Language" name="1">
                <van-field :value="LocalArr.Lang" label="Language" readonly clickable name="picker" input-align="right" @click="showLang = true" />
                <van-popup v-model="showLang" round position="bottom">
                  <van-picker show-toolbar :columns="LangArr" 
                    @cancel="showLang = false" 
                    @confirm="LangConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                  </van-popup>
              </van-collapse-item>
              <van-collapse-item title="Date Time" name="2">
                <van-field :value="LocalArr.Timezone" label="Timezone" readonly clickable name="picker" input-align="right" @click="showTimezone = true" />
                <van-popup v-model="showTimezone" round position="bottom">
                  <van-picker show-toolbar :columns="TimezoneArr" 
                    @cancel="showTimezone = false" 
                    @confirm="TimezoneConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                  </van-popup>
                  <van-field label="Date Time" v-model="LocalArr.Datetimes" clickable readonly input-align="right" @click="showDatetimes = true" />
                  <van-popup v-model="showDatetimes" round position="bottom">
                    <van-datetime-picker
                      v-model="currentDate"
                      type="datetime"
                      @cancel="showDatetimes = false"
                      @confirm="DatetimesConfirm"
                      :confirm-button-text="$t('OK')"
                      :cancel-button-text="$t('Cancel')"
                    />
                  </van-popup>
              </van-collapse-item>
              <van-collapse-item title="Charge Mode" name="3">
                <van-field :value="LocalArr.chargeMode" label="Mode Select" readonly clickable name="picker" input-align="right" @click="showchargeMode = true" />
                <van-popup v-model="showchargeMode" round position="bottom">
                  <van-picker show-toolbar :columns="chargeModeArr" 
                    @cancel="showchargeMode = false" 
                    @confirm="chargerModeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-field :value="LocalArr.ECOGearMode" label="ECOGear (A)" readonly clickable name="picker" input-align="right" @click="showECOGear = true" v-if="chargerModeCode==1" />
                <van-popup v-model="showECOGear" round position="bottom">
                  <van-picker show-toolbar :columns="ECOGearArr" 
                    @cancel="showECOGear = false" 
                    @confirm="ECOGearConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-field :value="LocalArr.GreenGearMode" label="GreenGear (A)" readonly clickable name="picker" input-align="right" @click="showGreenGear = true" v-if="chargerModeCode===0" />
                <van-popup v-model="showGreenGear" round position="bottom">
                  <van-picker show-toolbar :columns="GreenGearArr" 
                    @cancel="showGreenGear = false" 
                    @confirm="GreenGearConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
            </van-collapse-item>
            <van-collapse-item title="Max Current" name="4">
              <van-field v-model="LocalArr.UserSet_MaxCurrentValue" 
                  label="UserSet_MaxCurrent (A)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                  :rules="[{ validator:fixed1,message: `${$t('Range')}：40-300` }]" 
                />
            </van-collapse-item>
            <van-collapse-item title="Boost Mode" name="5">
                <van-field :value="LocalArr.BoostMode" label="Mode Select" readonly clickable name="picker" input-align="right" @click="showBoostMode = true" />
                <van-popup v-model="showBoostMode" round position="bottom">
                  <van-picker show-toolbar :columns="BoostModeArr" 
                    @cancel="showBoostMode = false" 
                    @confirm="BoostModeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-cell title="Fast Mode Start Time" :value="LocalArr.startTimeValue" @click="showStartTime=true" v-if="BoostModeCode==1" />
                <van-popup v-model="showStartTime" round position="bottom">
                  <van-datetime-picker v-model="currentStartTime" type="time" 
                    @cancel="showStartTime = false" 
                    @confirm="startTimeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-cell title="Fast Mode End Time" :value="LocalArr.endTimeValue" @click="showEndTime=true" v-if="BoostModeCode==1" />
                <van-popup v-model="showEndTime" round position="bottom">
                  <van-datetime-picker v-model="currentEndTime" type="time" 
                    @cancel="showEndTime = false" 
                    @confirm="endTimeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-field v-if="BoostModeCode==2"
                  v-model="LocalArr.Set_EQValue" 
                  label="Fast Mode Charge Energy (kWh)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                />
                <van-cell title="Fast Mode End Time" :value="LocalArr.Set_TimeValue" @click="showSet_Time=true" v-if="BoostModeCode==2" />
                <van-popup v-model="showSet_Time" round position="bottom">
                  <van-datetime-picker v-model="currentSet_Time" type="time" 
                    @cancel="showSet_Time = false" 
                    @confirm="Set_TimeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-field :value="LocalArr.RepeatMode" label="Repeat" readonly clickable name="picker" input-align="right" @click="showRepeat = true" v-if="BoostModeCode==1||BoostModeCode==2" />
                <van-popup v-model="showRepeat" round position="bottom">
                  <van-picker show-toolbar :columns="RepeatArr" 
                    @cancel="showRepeat = false" 
                    @confirm="RepeatConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-radio-group v-model="checked" v-if="RepeatModeCode==1">
                <van-cell-group>
                  <van-cell title="IsSingle" clickable @click="checked = '0'">
                    <template #right-icon>
                      <van-radio checked-color="#F39800" name="0" />
                    </template>
                  </van-cell>
                  <van-cell title="Repeat" clickable @click="checked = '1'">
                    <template #right-icon>
                      <van-radio checked-color="#F39800" name="1" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-radio-group>
            </van-collapse-item>
            <van-collapse-item title="Advance Setting" name="6">
              <van-field v-model="LocalArr.OverVoltSetValue" 
                  label="Max Voltage (V)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                  :rules="[{ validator:fixed2,message: `${$t('Range')}：260-300` }]" 
                />
                <van-field v-model="LocalArr.LowVoltSetValue" 
                  label="Min Voltage (V)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                  :rules="[{ validator:fixed3,message: `${$t('Range')}：80-160` }]" 
                />
                <van-field v-model="LocalArr.OverCurrentSetValue" 
                  label="Over Current (A)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                  :rules="[{ validator:fixed6,message: `${$t('Range')}：17-33` }]" 
                />
                <van-field v-model="LocalArr.PE_LeakCurrentValue" 
                  label="PE_Leak Current (mA)" 
                  type="digit" 
                  show-error 
                  name="validator" 
                  input-align="right" 
                  error-message-align="right" 
                  clearable 
                  :rules="[{ validator:fixed7,message: `${$t('Range')}：20-30` }]" 
                />
                <van-field :value="LocalArr.GridTransformerType" label="Grid Transformer Type" readonly clickable name="picker" input-align="right" @click="showGridTransformerType = true" />
                <van-popup v-model="showGridTransformerType" round position="bottom">
                  <van-picker show-toolbar :columns="GridTransformerTypeArr" 
                    @cancel="showGridTransformerType = false" 
                    @confirm="GridTransformerTypeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
                <van-field :value="LocalArr.StartChargeMode" label="StartChargeMode" readonly clickable name="picker" input-align="right" @click="showStartChargeMode = true" />
                <van-popup v-model="showStartChargeMode" round position="bottom">
                  <van-picker show-toolbar :columns="StartChargeModeArr" 
                    @cancel="showStartChargeMode = false" 
                    @confirm="StartChargeModeConfirm" 
                    :confirm-button-text="$t('OK')"
                    :cancel-button-text="$t('Cancel')" 
                  />
                </van-popup>
            </van-collapse-item>
          </van-collapse>
          <div class="chargerBtnBox">
            <van-button block round>{{$t('Save')}}</van-button>
          </div>
        </van-form>
        <van-divider>Reset</van-divider>
        <van-cell title="Restore default setting" class="margin">
          <template #right-icon>
            <van-button size="small" round class="setbtn" @click="RestoreDefaultConfirm">{{$t('Save')}}</van-button>
          </template>
        </van-cell>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { Dialog } from 'vant';
export default {
  data(){
    return {
      sn:localStorage.getItem('pileSn'),
      isLoading:false,
      activeNames:[],
      LangCode:'',
      LangArr:['English','Deutsch'],
      showLang:false,
      showTimezone:false,
      TimezoneArr:[-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12],
      showDatetimes:false,
      currentDate:'',
      showchargeMode:false,
      chargeModeArr:['Stop','Fast','ECO','Green'],
      chargerModeCode:'',
      showECOGear:false,
      ECOGearArr:[6,10,16,20,25],
      showGreenGear:false,
      GreenGearArr:[3,6],
      BoostModeCode:'',
      showBoostMode:false,
      BoostModeArr:['Off','Timer Boost-On','Smart Boost-On'],
      showStartTime:false,
      currentStartTime:'',
      showEndTime:false,
      currentEndTime:'',
      showSet_Time:false,
      currentSet_Time:'',
      checked:'',
      showRepeat:false,
      RepeatArr:['Never','Every day'],
      RepeatModeCode:'',
      MaxPower:'',
      showGridTransformerType:false,
      GridTransformerTypeArr:['CT','Meter','Remote Control'],
      GridTransformerTypeCode:'',
      showStartChargeMode:false,
      StartChargeModeCode:'',
      StartChargeModeArr:['Plug-in Start','Key Card Start'],
      ComType:'',
      FirmwareVersion_Main:'',
      Bootloader_Version:'',
      LocalArr:{
        Lang:'',
        Timezone:'',
        Datetimes:'',
        chargeMode:'',
        ECOGearMode:'',
        GreenGearMode:'',
        UserSet_MaxCurrentValue:'',
        OverVoltSetValue:'',
        LowVoltSetValue:'',
        OverCurrentSetValue:'',
        PE_LeakCurrentValue:'',
        GridTransformerType:'',
        StartChargeMode:'',
        BoostMode:'',
        startTimeValue:'',
        endTimeValue:'',
        Set_EQValue:'',
        Set_TimeValue:'',
        RepeatMode:''
      }
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:sessionStorage.getItem('setFrom')});
    },
    fixed1(val){
      let valid;
      if(val>=40&&val<=300){
        valid=true;
      }else{
        valid=false;
      }
      return valid;
    },
    fixed2(val){
      let valid;
      if(val>=260&&val<=300){
        valid=true;
      }else{
        valid=false;
      }
      return valid;
    },
    fixed3(val){
      let valid;
      if(val>=80&&val<=160){
        valid=true;
      }else{
        valid=false;
      }
      return valid;
    },
    fixed6(val){
      let valid;
      if(val>=17&&val<=33){
        valid=true;
      }else{
        valid=false;
      }
      return valid;
    },
    fixed7(val){
      let valid;
      if(val>=20&&val<=30){
        valid=true;
      }else{
        valid=false;
      }
      return valid;
    },
    LangConfirm(value,i){
      this.showLang=false;
      this.LocalArr.Lang=value;
      this.LangCode=i;
    },
    TimezoneConfirm(value,i){
      this.showTimezone=false;
      this.LocalArr.Timezone=value;
    },
    DatetimesConfirm(){
      this.showDatetimes = false;
      this.LocalArr.Datetimes = moment(this.currentDate).format("YYYY-MM-DD HH:mm");
    },
    chargerModeConfirm(value,i){
      this.showchargeMode=false;
      this.LocalArr.chargeMode=value;
      this.chargerModeCode=i;
      if(i===0){
        Dialog.confirm({
          title: 'Tip',
          message: '是否确认将模式设置为STOP?',
          confirmButtonText: this.$t('OK'),
          cancelButtonText:this.$t('Cancel')
        })
        .then(() => {
          this.chargerModeCode=i;
        })
        .catch(() => {
        });
      }
    },
    ECOGearConfirm(value,i){
      this.showECOGear=false;
      this.LocalArr.ECOGearMode=value;
    },
    GreenGearConfirm(value,i){
      this.showGreenGear=false;
      this.LocalArr.GreenGearMode=value;
    },
    BoostModeConfirm(value,i){
      this.showBoostMode=false;
      this.LocalArr.BoostMode=value;
      this.BoostModeCode=i;
    },
    startTimeConfirm(val){
      this.showStartTime=false;
      this.LocalArr.startTimeValue=val;
    },
    endTimeConfirm(val){
      this.showEndTime=false;
      this.LocalArr.endTimeValue=val;
    },
    Set_TimeConfirm(val){
      this.showSet_Time=false;
      this.LocalArr.Set_TimeValue=val;
    },
    RepeatConfirm(value,i){
      this.showRepeat=false;
      this.LocalArr.RepeatMode=value;
      this.RepeatModeCode=i;
    },
    GridTransformerTypeConfirm(value,i){
      this.showGridTransformerType=false;
      this.LocalArr.GridTransformerType=value;
      this.GridTransformerTypeCode=i;
    },
    StartChargeModeConfirm(value,i){
      this.showStartChargeMode=false;
      this.LocalArr.StartChargeMode=value;
      this.StartChargeModeCode=i;
    },
    //获取设置数据
    async getData(){
      this.comm.loadingShow();
      let datas = await this.SETAPI.setGetDataPT(localStorage.getItem('domain'),{'tokenId':localStorage.getItem('tokenId'),'sn':this.sn});
      if(datas.result!=null&&datas.result!="tokenId不合法!"){
        let dataArr=datas.result;
        this.LangCode=dataArr[111111111111];
        this.LocalArr.Lang=this.LangArr[this.LangCode];
        this.LocalArr.Timezone=dataArr[111111111111];
        this.LocalArr.Datetimes=moment(new Date()).format("YYYY-MM-DD HH:mm");
        this.chargerModeCode=dataArr[1];
        this.LocalArr.chargeMode=this.chargeModeArr[this.chargerModeCode];
        this.LocalArr.ECOGearMode=dataArr[2];
        this.LocalArr.GreenGearMode=dataArr[3];
        this.LocalArr.UserSet_MaxCurrentValue=dataArr[18];
        this.LocalArr.OverVoltSetValue=dataArr[5];
        this.LocalArr.LowVoltSetValue=dataArr[6];
        this.LocalArr.OverCurrentSetValue=dataArr[7];
        this.LocalArr.PE_LeakCurrentValue=dataArr[9];
        this.BoostModeCode=dataArr[11];
        this.LocalArr.BoostMode=this.BoostModeArr[this.BoostModeCode];

        let startTime1Handle= dataArr[12];
        let startTime1Handle1= parseInt(startTime1Handle/256);
        let startTime1Handle2=startTime1Handle%256;
        startTime1Handle1=parseInt(startTime1Handle1)>=10?startTime1Handle1:"0"+startTime1Handle1;
        startTime1Handle2=parseInt(startTime1Handle2)>=10?startTime1Handle2:"0"+startTime1Handle2;
        this.LocalArr.startTimeValue=`${startTime1Handle1}:${startTime1Handle2}`;

        let endTime1Handle= dataArr[13];
        let endTime1Handle1= parseInt(endTime1Handle/256);
        let endTime1Handle2=endTime1Handle%256;
        endTime1Handle1=parseInt(endTime1Handle1)>=10?endTime1Handle1:"0"+endTime1Handle1;
        endTime1Handle2=parseInt(endTime1Handle2)>=10?endTime1Handle2:"0"+endTime1Handle2;
        this.LocalArr.endTimeValue=`${endTime1Handle1}:${endTime1Handle2}`;

        this.LocalArr.Set_EQValue=dataArr[14];

        let Set_TimeValueHandle= dataArr[15];
        let Set_TimeValueHandle1= parseInt(Set_TimeValueHandle/256);
        let Set_TimeValueHandle2=Set_TimeValueHandle%256;
        Set_TimeValueHandle1=parseInt(Set_TimeValueHandle1)>=10?Set_TimeValueHandle1:"0"+Set_TimeValueHandle1;
        Set_TimeValueHandle2=parseInt(Set_TimeValueHandle2)>=10?Set_TimeValueHandle2:"0"+Set_TimeValueHandle2;
        this.LocalArr.Set_TimeValue=`${Set_TimeValueHandle1}:${Set_TimeValueHandle2}`;

        this.checked=dataArr[16]+'';

        this.MaxPower=dataArr[10];
        this.GridTransformerTypeCode=dataArr[0];
        this.LocalArr.GridTransformerType=this.GridTransformerTypeArr[this.GridTransformerTypeCode];
        this.StartChargeModeCode=dataArr[4];
        this.LocalArr.StartChargeMode=this.StartChargeModeArr[this.StartChargeModeCode];
        this.ComType=dataArr[17];
        this.FirmwareVersion_Main=dataArr[19];
        this.Bootloader_Version=dataArr[20];
      }else{
        this.comm.tipsShow('InvNoResponse');
      }
    },
    //设置
    async setCharger(){
      //datetime设置
      let DatetimesArr = (this.LocalArr.Datetimes).split(" ");
      let DatetimesArrA = DatetimesArr[0].split("-");
      let DatetimesArrB = DatetimesArr[1].split(":");
      let parmas = {
        'optType': 'setRTC',
        'sn': this.sn,
        'tokenId': localStorage.getItem('tokenId'),
        'YMDHMS': [DatetimesArrA[0]-2000,DatetimesArrA[1],DatetimesArrA[2],DatetimesArrB[0],DatetimesArrB[1]]
      };
      await SETAPI.setInvMachinePT(localStorage.getItem('domain'), parmas);
      //其他设置
      let StartTimeArr=this.LocalArr.startTimeValue.split(':');
      let EndTimeArr=this.LocalArr.endTimeValue.split(':');
      let Set_TimeArr=this.LocalArr.Set_TimeValue.split(':');
      let formData=[
        {'reg':21,'val':this.LangCode},
        {'reg':20,'val':this.Timezone},
        {'reg':2,'val':this.chargerModeCode},
        {'reg':3,'val':this.LocalArr.ECOGearMode},
        {'reg':4,'val':this.LocalArr.GreenGearMode},
        {'reg':18,'val':this.LocalArr.UserSet_MaxCurrentValue},
        {'reg':6,'val':this.LocalArr.OverVoltSetValue},
        {'reg':7,'val':this.LocalArr.LowVoltSetValue},
        {'reg':8,'val':this.LocalArr.OverCurrentSetValue},
        {'reg':10,'val':this.LocalArr.PE_LeakCurrentValue},
        {'reg':1,'val':this.GridTransformerTypeCode},
        {'reg':5,'val':this.StartChargeMode},
        {'reg':11,'val':this.BoostModeCode},
        {'reg':14,'val':this.LocalArr.Set_EQValue},
        {'reg':12,'val':parseInt(StartTimeArr[1])*256+parseInt(StartTimeArr[0])},
        {'reg':13,'val':parseInt(EndTimeArr[1])*256+parseInt(EndTimeArr[0])},
        {'reg':15,'val':parseInt(Set_TimeArr[1])*256+parseInt(Set_TimeArr[0])},
        {'reg':16,'val':this.checked}
      ];
      this.comm.setDataPT(18,formData);
    },
    //恢复出厂设置
    RestoreDefaultConfirm(){
      Dialog.confirm({
        title: 'Tip',
        message: '是否恢复出厂设置?',
        confirmButtonText: this.$t('OK'),
        cancelButtonText:this.$t('Cancel')
      })
      .then(() => {
        this.comm.setDataPT(1,{'reg':19,'val':1});
      })
      .catch(() => {
        // on cancel
      });
    },
    onRefresh(){
      this.isLoading = false;
      for(let i in this.LocalArr){
        this.LocalArr[i]='';
      }
      this.getData();
    }
  },
  mounted(){
    //this.getData();
  }
}
</script>

<style scoped lang="less">
.checkBox{
  margin: 10px 0;
}
.chargerBtnBox {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}
.margin{
  margin-bottom: 30px;
}
</style>
